61. 旋转链表
61. 旋转链表
Similar Question
leading to the advanced question
Solution Tips
可以考虑栈, 先进后出
方案一: 闭合为环
var rotateRight = function(head, k) {
if (k === 0 || !head || !head.next) {
return head;
}
let n = 1;
let cur = head;
while (cur.next) {
cur = cur.next;
n++;
}
let add = n - k % n;
if (add === n) {
return head;
}
cur.next = head;
while (add) {
cur = cur.next;
add--;
}
const ret = cur.next;
cur.next = null;
return ret;
};
是否闭合为环只是算法上更简约, 但是思路其实是一样的, 如果不闭合为环, 就是手动处理拼接操作而已.
方法二: 通过递归, 优化为一次循环
也不清楚是不是真的优化了